const App = {
    mixins: [Save],//配置文件，路径/utils/mixins.js
    data() {
        return {
            dataForm: {
                County_Nubmer: '232723',
            },
            childDataForm: [{
                action: '1',
                Main: '',
                fileList: [],
                Children: {
                    scenic_spot_attachment: []
                }
            }],
            childDataForm1: [{}],
            childDataForm2: [],
            childDataForm3:[{}],
            fileList: [],
            value: [],
            blue_plate: [],
            city: [],
            city1: [],
            value: [],
            scenic_spot_tags: [],
            tabs: [],//音频类型
            showDialog:false,
            fileUrl:'',
        };
    },
    mounted() {
        this.getCategory();
        this.changeCity(this.dataForm.County_Nubmer)
    },
    methods: {
        validator(rule, value, callback) {//校验身份证号
            if (value.length == 0) {
                callback(new Error('请选择景区标签'));
            } else {
                callback();
            }
        },
        getData(nodeKey) {//查询
            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/generalBusiness/generalQueryByTableNameWithOriginal`,
                method: "post",
                data: {
                    Data: 'scenic_spot',
                    Condition: `Scenic_Spot_SerialNumber='${nodeKey}'`,
                },
                success: (res) => {
                    this.dataForm = res[0]
                },
                complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest)
                },
            });
            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/generalBusiness/generalQueryByTableNameWithOriginal`,
                method: "post",
                data: {
                    Data: 'scenic_spot_mapping_tags',
                    Condition: `Scenic_Spot_SerialNumber='${nodeKey}'`,
                },
                success: (res) => {
                    console.log(res);
                    this.childDataForm2 = res;
                    this.value = res.filter(i => i.Row_Status != "1").map(i => i.Scenic_Spot_Tag_SerialNumber);
                },
                complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest)
                },
            });
            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/generalBusiness/generalQueryByTableNameWithOriginal`,
                method: "post",
                data: {
                    Data: 'scenic_spot_strategy',
                    Condition: `Scenic_Spot_SerialNumber='${nodeKey}'`,
                },
                success: (res) => {
                    console.log(res);
                    this.childDataForm1 = res;
                },
                complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest)
                },
            });
            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/generalBusiness/generalQueryByTableNameWithOriginal`,
                method: "post",
                data: {
                    Data: 'scenic_spot_QR',
                    Condition: `Scenic_Spot_SerialNumber='${nodeKey}'`,
                },
                success: (res) => {
                    console.log(res);
                    this.childDataForm3 = res;
                },
                complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest)
                },
            });
            
            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/generalBusiness/generalQueryByTableNameWithOriginal`,
                method: "post",
                data: {
                    Data: 'scenic_spot_detail',
                    Condition: `Scenic_Spot_SerialNumber='${nodeKey}'`,
                },
                success: (res) => {
                    $.ajax({
                        headers: requestHeaders(),
                        url: `${mh}/generalBusiness/generalQueryByTableNameWithOriginal`,
                        method: "post",
                        data: {
                            Data: 'scenic_spot_attachment',
                            Condition: `Row_Status='0' AND Scenic_Spot_Detail_SerialNumber IN (${res.map(i => "'" + i.Scenic_Spot_Detail_SerialNumber + "'").join(',')})`,
                        },
                        success: (data) => {
                            res.forEach(item => {
                                item.action = '1';
                                item.fileList = [];
                                item.Children = { scenic_spot_attachment: [] };
                                data.filter(i => i.Scenic_Spot_Detail_SerialNumber == item.Scenic_Spot_Detail_SerialNumber).forEach(obj => {
                                    obj.name = obj.Attachment_Name + "（磁盘文件名:" + obj.Attachment_URL + "）";
                                    item.fileList.push(obj);
                                    item.Children.scenic_spot_attachment.push(obj);
                                })
                            })
                            this.childDataForm = res;
                        },
                        complete: (XMLHttpRequest) => {
                            requestPretreatment(XMLHttpRequest)
                        },
                    });
                },
                complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest)
                },
            });
        },
        getCategory() {
            $.ajax({
                url: `${absolutepath()}api/tour_guide.json`,
                method: "GET",
                success: (data) => {
                    this.tabs = data;
                },
                dataType: "json",
            });
            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/generalBusiness/generalQueryByTableName`,
                type: "POST",
                data: {
                    Data: "blue_plate_information",
                    Condition: "Row_Status='0'",
                },
                success: (data) => {
                    this.blue_plate = data; // 直接使用 this
                },
                complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json",
            });
            $.ajax({
                headers: requestHeaders(),
                url: `${mh}/generalBusiness/generalQueryByTableName`,
                type: "POST",
                data: {
                    Data: "scenic_spot_tags",
                    Condition: "Row_Status='0'",
                },
                success: (data) => {
                    this.scenic_spot_tags = data; // 直接使用 this
                },
                complete: (XMLHttpRequest) => {
                    requestPretreatment(XMLHttpRequest);
                },
                dataType: "json",
            });
            $.ajax({
                url: `${absolutepath()}api/Districtjl.json`,
                method: "get",
                success: (data) => {
                    data.forEach((item) => {
                        item.children.forEach((ite) => {
                            ite.children.forEach((it) => {
                                it.children = undefined;
                            });
                        });
                    });
                    this.city = data;
                }
            });
        },
        changeCity(val) {
            if (val) {
                this.dataForm.Province_Number = val.substring(0, 2) + '0000';
                this.dataForm.City_Number = val.substring(0, 4) + '00';
                $.ajax({
                    headers: requestHeaders(),
                    url: `${mh}/clientOperation/getDistrictTree`,
                    type: "GET",
                    data: {
                        DistrictCode: val,
                    },
                    success: (data) => {
                        this.city1 = data[0].children;
                    },
                    complete: (XMLHttpRequest) => {
                        requestPretreatment(XMLHttpRequest);
                    },
                    dataType: "json",
                });
            } else {
                this.dataForm.Province_Number = '';
                this.dataForm.City_Number = '';
                this.dataForm.County_Nubmer = '';
                this.dataForm.Town_Number = '';
                this.dataForm.Village_SerialNumber = '';
            }
        },
        changeCity1(val) {
            this.dataForm.Town_Number = val.substring(0, 9);
        },
        InputCoords(val) {
            //
            const coordRegex = /^\[\[-?\d+\.?\d*,\s*-?\d+\.?\d*\]+(,\[-?\d+\.?\d*,\s*-?\d+\.?\d*\])*\]$/;
            if (!coordRegex.test(val)) {
                this.value = [];
                return false;
            }
            try {
                const coordinates = JSON.parse(val);

                if (!Array.isArray(coordinates)) {
                    return false;
                }

                for (const point of coordinates) {
                    if (!Array.isArray(point) || point.length !== 2) {
                        return false;
                    }

                    for (const coord of point) {
                        if (typeof coord !== 'number' && isNaN(parseFloat(coord))) {
                            return false;
                        }
                    }
                }
                $.ajax({
                    url: `${y}/getBluePlateAsCoordsAction`,
                    type: "POST",
                    data: {
                        Data: val
                    },
                    success: ({ Status, Data }) => {
                        if (Status == 'success' && Data.length > 0) {
                            this.value = Data.map(i => i.Blue_Plate_SerialNumber)
                        }
                    },
                    dataType: "json",
                });
            } catch (e) {
                return false;
            }
        },
        success(row, res, item) {
            let obj = {
                uid: row.uid,
                Scenic_Spot_Detail_SerialNumber: item.Scenic_Spot_Detail_SerialNumber,
                Attachment_Type: item.action,
                Attachment_URL: res.fileName,
                Attachment_Name: row.name,
                Temp_Path: res.tempPath,
            }
            item.Children.scenic_spot_attachment.push(obj)
            // item.fileList.push(obj)
        },
        remove(row, item) {
            if (!Object.keys(row).some(item => item.includes('_Original'))) {
                item.Children.scenic_spot_attachment = item.Children.scenic_spot_attachment.filter(i => i.uid != row.uid);
            } else {
                let obj = item.Children.scenic_spot_attachment.filter(i => i.Attachment_SerialNumber == row.Attachment_SerialNumber)[0];
                obj.Row_Status = '1'
            }
        },
        preview(row){
            this.fileUrl = photo + row.Attachment_URL;
            this.showDialog = true
        },
        handleAdd(formName) {
            if (this.action === 'Add') {
                if (formName == 'childDataForm') {
                    this[formName].push({
                        action: '1',
                        Main: '',
                        fileList: [],
                        Children: {
                            scenic_spot_attachment: []
                        }
                    })
                } else {
                    this[formName].push({})
                }
            } else if (this.action === 'Modify') {
                let lJSONObject_Data_Options = new Object();
                lJSONObject_Data_Options = JSON.parse(document.getElementById("MainTable").getAttribute("data-options"));
                let ls_primary_key = lJSONObject_Data_Options.primary_key;
                let lJSONObject_Data = new Object();
                if (formName == 'childDataForm') {
                    lJSONObject_Data = {
                        fileList: [],
                        Children: {
                            scenic_spot_attachment: []
                        }
                    }
                }
                lJSONObject_Data[ls_primary_key] = this.nodeKey;
                this[formName].push(lJSONObject_Data);
            }
        },
        async handleSubmit() {
            const allValid = await this.validateAllForms();
            if (allValid) {
                this.loading = true;
                let ls_URL = window.location.href;
                const action = getQueryObject(ls_URL, "action");   // 获取 action 参数
                let lJSONObject_Data_Options = new Object();
                lJSONObject_Data_Options = JSON.parse(document.getElementById("MainTable").getAttribute("data-options"));

                let ls_MainTableName = lJSONObject_Data_Options.TableName;
                let ls_DataForm = lJSONObject_Data_Options.form;
                let ls_primary_key = lJSONObject_Data_Options.primary_key;
                //没有子表下面内容就会报错，try/catch抛出异常
                this.childDataForm.forEach((item, index) => {
                    item.Sort = index + 1;
                });
                if (action == "Add") {
                    this.value.forEach((item) => {
                        this.childDataForm2.push({
                            Scenic_Spot_Tag_SerialNumber: item,
                        });
                    });
                } else if (action == "Modify") {
                    this.value.forEach((item) => {
                        let obj = this.childDataForm2.filter(i => i.Scenic_Spot_Tag_SerialNumber == item)[0];
                        if (obj) {
                            obj.Row_Status = "0";
                        } else {
                            this.childDataForm2.push({
                                Scenic_Spot_SerialNumber: this.dataForm.Scenic_Spot_SerialNumber,
                                Scenic_Spot_Tag_SerialNumber: item,
                            });
                        }
                    });
                    this.childDataForm2.forEach((item) => {
                        if (!this.value.some((i) => i == item.Scenic_Spot_Tag_SerialNumber)) {
                            item.Row_Status = "1";
                        }
                    });
                }
                try {
                    //可能涉及多个子表
                    document.getElementById("ChildTable").querySelectorAll(".el-descriptions").forEach(item => {
                        if (item.hasAttribute('data-options')) {
                            let lJSONObject_ChildData_Options = new Object();
                            lJSONObject_ChildData_Options = JSON.parse(item.getAttribute("data-options"));

                            let ls_ChildTableName = lJSONObject_ChildData_Options.TableName;
                            let ls_ChildDataForm = lJSONObject_ChildData_Options.form;
                            // let ls_ParentTableName = lJSONObject_ChildData_Options.ParentTableName;
                            if (this[ls_DataForm][ls_primary_key]) {
                                this[ls_ChildDataForm].forEach(item => {
                                    item[ls_primary_key] = this[ls_DataForm][ls_primary_key];
                                })
                            }
                            //建立子表结构体
                            let JSONArray_ChildRecord = new Array();
                            JSONArray_ChildRecord = this[ls_ChildDataForm];
                            if (!this[ls_DataForm].Children) {
                                this[ls_DataForm].Children = new Object();
                            }
                            this[ls_DataForm].Children[ls_ChildTableName] = JSONArray_ChildRecord;
                        }
                    })
                } catch (error) {

                }
                //建立新增提交结构
                let dataForm =  this[ls_DataForm];
                let lJSONObject_DataSet = new Object();
                if (action == 'Add') {
                    if (this.nodeKey) {
                        dataForm.Parent_SerialNumber = this.nodeKey;
                    }
                    let lJSONArray_Record = new Array();
                    lJSONArray_Record.push(dataForm);
                    let lJSONObject_Table = new Object();
                    lJSONObject_Table[ls_MainTableName] = lJSONArray_Record;
                    lJSONObject_DataSet[action] = lJSONObject_Table;
                } else if (action == 'Modify') {

                    //1.将孙表提出 来
                    let scenic_spot_attachment = [];
                    dataForm.Children.scenic_spot_detail.filter(i => i.Row_Status != '1').forEach(item => {
                        //判断当前子表是否为新增/如果为新增，则不用提出来，通过下面的方法筛出Add和Modify
                        if (Object.keys(item).some(item => item.includes('_Original'))) {
                            scenic_spot_attachment = [...scenic_spot_attachment, ...item.Children.scenic_spot_attachment];
                            delete item.Children.scenic_spot_attachment;
                        }
                    })


                    const { add, modify } = this.deal(dataForm);
                    let lJSONArray_Record = new Array();
                    lJSONArray_Record.push(modify);

                    let lJSONObject_Table = new Object();
                    lJSONObject_Table[ls_MainTableName] = lJSONArray_Record;

                    lJSONObject_DataSet[action] = lJSONObject_Table;
                    lJSONObject_DataSet['Add'] = new Object();
                    if (add != null) {
                        let lJSONArray_Record_Add = new Array();
                        lJSONArray_Record_Add.push(add);

                        let lJSONObject_Table_Add = new Object();
                        lJSONObject_Table_Add[ls_MainTableName] = lJSONArray_Record_Add;

                        lJSONObject_DataSet['Add'] = lJSONObject_Table_Add;
                    }

                    lJSONObject_DataSet['Add']['scenic_spot_attachment'] = [];
                    lJSONObject_DataSet[action]['scenic_spot_attachment'] = [];

                    for (let i = 0; i < scenic_spot_attachment.length; i++) {
                        const obj = scenic_spot_attachment[i];
                        if (!Object.keys(obj).some(item => item.includes('_Original'))) {
                            lJSONObject_DataSet['Add']['scenic_spot_attachment'].push(obj)
                        } else {
                            lJSONObject_DataSet[action]['scenic_spot_attachment'].push(obj)
                        }
                    }
                }
                let Operation_Main = JSON.stringify(deepClone(lJSONObject_DataSet));
                lJSONObject_DataSet['Add']['base_operation_log'] = [{
                    Operation_Type: '0',
                    Operation_Path: this.relativePath,
                    Operation_Main,
                    Operation_Interface: "generalSaveByRequestBody",
                    Operation_IP: getIpAddress()
                }]
                submitSave(lJSONObject_DataSet, (res) => {
                    if (res.Status == 'success') {
                        window.location.href = './index.html'
                        // window.history.go(-1);
                    }
                    this.loading = false;
                })
                // $.ajax({
                //     headers: requestHeaders("JSON"),
                //     url: `${mh}/generalBusiness/generalSaveByRequestBody`,
                //     method: "post",
                //     data: JSON.stringify({
                //         Data: lJSONObject_DataSet,
                //     }),
                //     success: (res) => {
                //         if (res.Status == 'success') {
                //             window.location.href = './index.html'
                //             // window.history.go(-1);
                //         }
                //     },
                //     complete: (XMLHttpRequest) => {
                //         this.loading = false;
                //         requestPretreatment(XMLHttpRequest)
                //     }
                // });
            } else {
                this.$message({
                    message: '存在未填写的必填项！',
                    type: 'warning'
                });
            }
        },
    },
};
const { createApp, ref } = Vue;
const app = createApp(App);
app.use(ElementPlus, { locale: zhCn });
//这种方式是引入全部图标，无需单个引入
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
    app.component(key, component);
}
app.component('yl-upload', ylUpload);
app.component('yl-cascader', ylCascader)
app.component('yl-text-editor', ylTextEditor);
app.component('yl-online-preview',ylOnlinePreview)
const ElMessage = ElementPlus.ElMessage;
app.mount("#app");
